<?php

namespace App\Console\Commands;

use App;
use Illuminate\Console\Command;
use swoole_server;

class TcpServer extends Command
{
    private $_serv;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'swoole:tcpserver {action=start}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Start a tcpserver';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $arg = $this->argument('action');
        switch ($arg){
            case 'start':
                $this->info('swoole observer started');
                $this->start();
                break;
        }
    }

    private function start(){
        $this->_serv = new swoole_server(env('WEB_HOST'), env('WEB_PORT'));
        $this->_serv->set([
                'worker_num' => 2,
                'daemonize' => false,
                'max_conn ' => env('MAX_CONN'),
                'tcp_defer_accept ' => 5,
                'heartbeat_check_interval' => 35
            ]);

        //打开内部监听端口
        $inner = App::make('App\Handlers\InnerHandler');
        $innerPort = $this->_serv->listen("0.0.0.0", env('WEB_INNER_PORT'), SWOOLE_SOCK_TCP);
        $innerPort->on("Receive", [$inner, 'onReceive']);

        $handler = App::make('App\Handlers\SwooleHandler');
        $this->_serv->on('Start', [$handler, 'onStart']);
        $this->_serv->on('Connect', [$handler, 'onConnect']);
        $this->_serv->on('Receive', [$handler, 'onReceive']);
        $this->_serv->on('Close', [$handler, 'onClose']);

        $this->_serv->start();
    }


}
